/**
 * Created by John on 2016/7/15.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();
var myDB = null;

mongo.connect('mongodb://localhost/', function (err, db) {
    myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        console.log('Before Inserting:');
        showDocs(collection, addSelfie);
    });
});

function showDocs(collection, callback) {
    var query = {category: 'New'};
    collection.find(query, function (err, items) {
        items.toArray(function (err, items) {
            for (var i = 0; i < items.length; i++) {
                console.log(items[i]);
            }
            callback(collection);
        });
    });
}

function addSelfie(collection) {
    var selfie = {
        word: 'selfie',
        first: 's',
        last: 'e',
        size: 6,
        letters: ['s', 'e', 'l', 'f', 'i'],
        stats: {vowels: 3, consonants: 3},
        charsets: [
            {type: 'consonants', chars: ['s', 'l', 'f']},
            {type: 'vowels', chars: ['e', 'i']}

        ],
        category: 'New'
    };

    var options = {w: 1, wtimeout: 5 * 1000, journal: true, fsync: false};

    collection.insert(selfie, options, function (err, items) {
        console.log();
        console.log('Inserting One Results:');
        console.log(items);
        console.log();
        console.log('After Inserting One:');
        showDocs(collection, addGoogleAndTweet);
    });
}

function addGoogleAndTweet(collection) {
    var tweet = {
        word: 'tweet',
        first: 't',
        last: 't',
        size: 5,
        letters: ['t', 'w', 'e'],
        stats: {vowels: 2, consonants: 3},
        charsets: [
            {type: 'consonants', chars: ['t', 'w']},
            {type: 'vowels', chars: ['e']}

        ],
        category: 'New'
    };

    var google = {
        word: 'google',
        first: 'g',
        last: 'e',
        size: 6,
        letters: ['g', 'o', 'l', 'e'],
        stats: {vowels: 3, consonants: 3},
        charsets: [
            {type: 'consonants', chars: ['g', 'l']},
            {type: 'vowels', chars: ['o', 'e']}

        ],
        category: 'New'
    };

    var options = {w: 1, wtimeout: 5 * 1000, journal: true, fsync: false};

    collection.insert([tweet, google], options, function (err, items) {
        console.log();
        console.log('Inserting One Results:');
        console.log(items);
        console.log();
        console.log('After Inserting One:');
        showDocs(collection, close);
    });
}

function close() {
    setTimeout(function () {
        myDB.close();
    }, 3000);
}